//
//  JSBridgeViewController.m
//  iOS-Learning-Demo
//
//  Created by yuan xiaodong on 2021/9/22.
//  Copyright © 2021 yuan. All rights reserved.
//

#import "JSBridgeViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "JSBridgeHandler.h"

@interface JSBridgeViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) JSBridgeHandler *bridgeHandler;

@end

@implementation JSBridgeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"JSBridge";
    [self.view addSubview:self.webView];

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index"
                                                          ofType:@"html"];
    NSString * htmlContent = [NSString stringWithContentsOfFile:htmlPath
                                                    encoding:NSUTF8StringEncoding
                                                       error:nil];
    [self.webView loadHTMLString:htmlContent baseURL:baseURL];
}

- (void)exaluateJSWithStr:(NSString *)scriptStr{
    [self.webView evaluateJavaScript:scriptStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error){
            NSLog(@"执行JS失败：%@",scriptStr);
        }
    }];
}

- (JSBridgeHandler *)bridgeHandler{
    if (!_bridgeHandler){
        _bridgeHandler = JSBridgeHandler.new;
        @weakify(self)
        [_bridgeHandler setHandleBlock:^(NSString * _Nonnull scriptStr) {
            @strongify(self)
            [self exaluateJSWithStr:scriptStr];
        }];
    }
    return _bridgeHandler;
}

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [[WKUserContentController alloc] init];
        
        WKUserContentController *content = configuration.userContentController;
        [content addScriptMessageHandler:self.bridgeHandler name:@"JSBridge"];
    
        NSString *printContent = @"syncPlatform_iOS(true)";
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:printContent injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [content addUserScript:userScript];
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }
    return _webView;
}

@end
